package com.suntoon.framework.util;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2021年06月25日 14时36分31秒
 * @Description: 随机生成数字、字母
 */

public class RandomUtil {
    public static final String BASE_NUMBER = "0123456789";

    public static final String BASE_MALL_CHAR = "abcdefghijklmnopqrstuvwxyz";

    public static final String BASE_BIG_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String BASE_SMALL_CHAR_NUMBER = "abcdefghijklmnopqrstuvwxyz0123456789";

    public static final String BASE_BIG_CHAR_NUMBER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public static final String BASE_BIG_SMALL_CHAR_NUMBER = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**
     * 随机生成指定长度的数字
     *
     * @param length
     * @return
     */
    public static String randomNumber(int length) {
        return randomString(BASE_NUMBER, length);
    }

    /**
     * 随机生成指定长度的小写字母
     *
     * @param length
     * @return
     */
    public static String randomSmallLetter(int length) {
        return randomString(BASE_MALL_CHAR, length);
    }

    /**
     * 随机生成指定长度的大写字母
     *
     * @param length
     * @return
     */
    public static String randomCapitalLetter(int length) {
        return randomString(BASE_BIG_CHAR, length);
    }

    /**
     * 随机生成指定长度的小写字母 + 数字
     *
     * @param length
     * @return
     */
    public static String randomSmallLetterNumber(int length) {
        return randomString(BASE_SMALL_CHAR_NUMBER, length);
    }

    /**
     * 随机生成指定长度的大写字母 + 数字
     *
     * @param length
     * @return
     */
    public static String randomCapitalLetterNumber(int length) {
        return randomString(BASE_BIG_CHAR_NUMBER, length);
    }

    /**
     * 随机生成指定长度的大小写字母 + 数字
     *
     * @param length
     * @return
     */
    public static String randomCapitalAndSmallLetterNumber(int length) {
        return randomString(BASE_BIG_SMALL_CHAR_NUMBER, length);
    }

    /**
     * 生产指定长度的随机字符串
     *
     * @param baseString
     * @param length
     * @return
     */
    public static String randomString(String baseString, int length) {
        if (StrUtil.isEmpty(baseString)) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder(length);
            if (length < 1) {
                length = 1;
            }
            int baseLength = baseString.length();

            for (int i = 0; i < length; ++i) {
                int number = randomInt(baseLength);
                sb.append(baseString.charAt(number));
            }

            return sb.toString();
        }
    }

    public static int randomInt(int limit) {
        return getRandom().nextInt(limit);
    }

    public static ThreadLocalRandom getRandom() {
        return ThreadLocalRandom.current();
    }
}
